import './style.scss';
import React, { Component } from 'react';
import { DIST } from 'conf';
import Tags from '../../common/Tags';
import Colors from '../../common/Color';
import Listbox from '../../common/Listbox';
import Pages from '../../common/Pages';

import { getTpls, getTypes } from '@/server/source';

export default class Index extends Component {

    constructor(props) {
        super(props);
        this.state = {
            tags: null,
            data: [],
            type: 1
        }
    }

    componentDidMount() {
        this.getTpys();
        $(document).on('color', (e, color) => {
            $('.tpls').find('section').each(function(elem) {
                let style = $(this).attr('style');
                if(/(rgb)|#/.test(style)) {
                    if($(this).attr('background') !== -1) {
                        style = style.replace(/background-color:rgb\(.+?\)/g, 'background-color:' + color);
                        style = style.replace(/background-color:#[a-zA-Z0-9]+/g, 'background-color:' + color);
                    }
                }
                $(this).attr('style', style);
            });
        });
    }

    componentWillUnmount() {
        $(document).off('color');
    }

    // 获取分类
    getTpys = () => {
        getTypes({ type: 1 }).then(res => {
            this.setState({
                tags: res.data.reverse()
            });
        });
    }

    // 获取模板
    getTpls = (num) => {
        return getTpls({
            type: this.state.type,
            pageSize: 20,
            pageNum: num || 1
        }).then(res => {
            if (res.success) {
                this.setState({
                    data: res.data
                });
                return res;
            }
        });
    }

    // 切换tags
    changeTags = e => {
        this.setState({
            type: e.id
        });
    }

    // 选择模板
    selectTpl = e => {
        UE.getEditor('container').setContent($(e.currentTarget).html(), true);
    }

    render() {
        let { tags, data, type } = this.state;
        return (
            <div className="styletpl">
                <Tags data={tags} active={'标题'} onChange={this.changeTags} />
                <Colors />
                <Listbox top={180}>
                    <div className="tpls">
                        <ul>
                            {
                                data.map(elem => {
                                    return <li onClick={e => { this.selectTpl(e); }} key={elem.id} dangerouslySetInnerHTML={{ __html: elem.data }}></li>;
                                })
                            }
                        </ul>
                    </div>
                </Listbox>
                <Pages key={type} ajax={this.getTpls} />
            </div>
        );
    }
}